import React, { useContext, useEffect, useState } from 'react';
import LocaleContext from "../libs/locale";
import WalletContext from "../libs/wallet";
import {Alert, Dimensions, TouchableOpacity, View, ImageBackground, ScrollView, Linking} from "react-native";
import {Text} from "react-native-elements";
import {getERCBalance, getETHAddress, GetRedEnvelope, QueryRedEnvelope} from "../libs/nodes";
import Clipboard from "@react-native-community/clipboard";
import Toast from "react-native-simple-toast";
import MyAlert from "../components/MyAlert";
import WebBrowserInfo from "../screens/WebBrowserInfo"

import one from '../assets/nineBox/1.png';
import two from '../assets/nineBox/2.png';
import three from '../assets/nineBox/3.png';
import four from '../assets/nineBox/4.png';
import five from '../assets/nineBox/5.png';
import six from '../assets/nineBox/6.png';
import seven from '../assets/nineBox/7.png';
import daomin from "../assets/nineBox/daomin.png"
import RedEnvelopeLoad from "./RedEnvelopeLoad";
import {constansts} from "../libs/constansts";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Sound from "react-native-sound";
import {addRedEnvelopeGet, getRedEnvelopeGet} from "../libs/pendingTxs";
import {useFocusEffect} from "@react-navigation/native";
import {keyPairFromSeed, sign as keyPairSign} from "../libs/keyPair";
import CryptoJS from "crypto-js";

const {width,height,scale} = Dimensions.get("window");

const SmartXApp = ({navigation}:any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [refresh, setRefresh] = useState(true);
    const [ETHAddress,setETHAddress] = useState("");
    const [ERCBalance,setERCBalance] = useState("0.00");
    const [ERCStatus,setERCStatus] = useState("");
    const [BTNName,setBTNName] = useState("");

    //MyAlert测试 以及MyAler参数
    const [showMyAlert,setShowMyAlert] = useState(false);
    const [AlertInfo,setAlertInfo] = useState("");
    const [AlertTitle,setAlertTitle] = useState("提示");
    const [BTNcount,setBTNcount] = useState(1);
    const [Infoline,setInfoline] = useState(1);



    const onCopy = ( data:any) => {
        if(data=="")
            return;
        Clipboard.setString(data);
        Toast.show(locale?._('copied') as any);
    };


    async function showETHAddress() {
        try {
            const res = await getETHAddress(wallet.seed, wallet.address);
            setETHAddress(res.dict.erc);
            setBTNName(locale?._('copy').toString() || "")
            const ERCDict = await getERCBalance(res.dict.erc);
            console.log("ERCDict="+ERCDict)
            if(ERCDict==false)
            {
                setERCBalance("0.00");
                return ;
            }
            setERCStatus(ERCDict.fstatus);
            console.log("ERCDict.fstatus="+ERCDict.fstatus)
            if(ERCDict.fstatus=="2")
            setBTNName(locale?._("DApp.MappingCompleted").toString() as any);
            const ERCBalance = ERCDict.balance;
            setERCBalance(ERCBalance);
        }catch (e) {
            setBTNName(locale?._('DApp.applyETHAddress').toString() || "");
        }
    }

    function mainBTN() {
        if(BTNName==locale?._('copy').toString())
        {
            onCopy(ETHAddress);
        }
        else if(BTNName==locale?._("DApp.MappingCompleted").toString())
        {
        }
        else
        {
            showETHAddress();
        }
    }

    useEffect(()=>{
        const work = async () => {
            (constansts.RedEnvelopeHash as any) = await AsyncStorage.getItem('@RedEnvelopeHash');
            (constansts.RedEnvelopeNumber as any) = await AsyncStorage.getItem('@RedEnvelopeNum');
            (constansts.RedEnvelopeTotal as any) = await AsyncStorage.getItem('@RedEnvelopeAmount');
        }
        work();
    },[])
    useEffect(()=>{
        mainBTN();
    },[])

    const AlertBack = (res:boolean)=>{
        setShowMyAlert(false);
        console.log(res)
    }


    //测试红包领取页面
    const [showRedEnvelopeLoad,setShowRedEnvelopeLoad] = useState(false);
    const [pkgid,setPkgid] = useState("");
    const [coverTxt,setCoverTxt] = useState("");
    const [sender,setSender] = useState(true)//红包的发送人
    const [loadType,setLoadType] = useState('0');

    //添加进代币的内容
    const [openRedEnvelopeConAddress,setOpenRedEnvelopeConAddress] = useState('');
    const [openRedEnvelopeTokenName,setOpenRedEnvelopeTokenName] = useState('');
    const [openRedEnvelopeUrl,setOpenRedEnvelopeUrl] = useState('');

    const playSound = (name:string) =>{
        Sound.setCategory('Playback') // 在静音模式下启用播放'
        let whoosh = new Sound(name, Sound.MAIN_BUNDLE, (error) => {
            whoosh.play((success) => {
                whoosh.release()
            })
        })
    }
    const getClipboardString = async () => {
        const content = await Clipboard.getString();
        return content;
    }
    const RedEnvelopeLoadBack =  (res: any) => {
        setShowRedEnvelopeLoad(false);
        console.log(res)
        if (res == "0") {
        } else if (res == "1") {
            playSound("openred.mp3");
            GetRedEnvelope(wallet.address, pkgid).then(
                async ()=>{
                    console.log(`openRedEnvelopeConAddress=${openRedEnvelopeConAddress}`)
                    if(openRedEnvelopeConAddress !== "")
                    {
                        for(var i=0;i<(constansts.addTokens).length;i++)
                        {
                            //如果有相同的就只接跳出
                            if( (constansts.addTokens[i] as any).address===openRedEnvelopeConAddress)
                            {
                                break;
                            }
                            //到最后一个并且不相同 添加再退出
                            if((constansts.addTokens[i] as any).address!==openRedEnvelopeConAddress && i === ((constansts.addTokens).length - 1))
                            {
                                (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                                console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                                await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                                break;
                            }
                        }
                        if((constansts.addTokens).length === 0 )
                        {
                            (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                            console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                            await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                        }

                    }

                    navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
                    await addRedEnvelopeGet(pkgid);
                }
            );

        } else if (res == "2") {
            navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
        }
    }
    const work2 = async () => {
        // await AsyncStorage.setItem('@addRedEnvelopeGet', "[]")
        const ClipboardString = await getClipboardString();
        // console.log("剪贴板的内容==》" + ClipboardString);
        if (ClipboardString == "") {
            return;
        }
        var RedEnvelopeReceivedList = await getRedEnvelopeGet();
        // console.log("数组信息"+JSON.stringify(RedEnvelopeReceivedList))
        if (ClipboardString == "") {
            return;
        }
        var password ="";
        if(ClipboardString.indexOf("(")!==-1&&ClipboardString.indexOf(")")!==-1)
        {
            password = ClipboardString.slice(ClipboardString.indexOf("(")+1,ClipboardString.indexOf(")"));
        }
        else
        {
            password=ClipboardString;
        }
        if (RedEnvelopeReceivedList.indexOf(password) !== -1 || password.length!==15) {
            return;
        }

        try {
            var result: any = await QueryRedEnvelope(password);
            var sender = result.dict.nickname || result.dict.sender;
            setOpenRedEnvelopeConAddress (result.dict.type || "");
            setOpenRedEnvelopeTokenName(result.dict.coinname || "");
            setOpenRedEnvelopeUrl ( result.dict.url || "");
            setCoverTxt(result.dict.desc);
            if (sender !== "") {
                await addRedEnvelopeGet(password);
                setPkgid(password);
                setSender(sender);
                var temp = 0;//0是红包还有可以强，并且没抢过这个红包。   1是抢过这个红包了。   2是红包没了，手速慢了
                if (result.pkgitems.length < parseInt(result.dict.number))//红包还有，里面区分0和1
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                        }
                    } else {
                        temp = 0;
                    }

                } else if (result.pkgitems.length >= parseInt(result.dict.number)) //红包没了 ，里面区分抢过了1和没抢过2
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                            if (i == result.pkgitems.length - 1) {
                                temp = 2;
                            }
                        }
                    } else {
                        temp = 2;
                    }
                } else {
                    temp = 0;
                }
                if (temp == 1) {
                    Toast.show("该红包您已经抢过了")
                    navigation.navigate('RedEnvelopeInfo', {pkgid: password});
                } else {
                    console.log("进入这里了呀")
                    setLoadType(temp.toString())
                    setShowRedEnvelopeLoad(true);
                }

            } else {
                // Alert.alert("", "没有此口令。");
            }
        } catch (e) {
            console.log("抢红包错误==》" + e)
            return;
        }

    }
    useFocusEffect(
        React.useCallback(() => {
            const t = setInterval(work2,1000);//监控剪贴板
            return ()=> {
                clearInterval(t)
            };
        }, [])
    );


    return(
        <View style={{backgroundColor:"white",flex:1,alignItems:"center"}}>
            <View style={{backgroundColor:'#7367E3',height:0.2073*height,width:width}}>
                <Text style={{fontWeight:"bold",fontSize:25,color:'white',marginTop:25}}>   {locale?._('DApp.SmartXAPP')}</Text>
            </View>
            <View  style={{backgroundColor:"#F3F4F5",flex:1,width:width,alignItems:"center"}}>
                <View style={{width:width*0.92,height:height*0.264,borderRadius:16,backgroundColor:'white',marginTop:height*(-0.1),alignItems:"center"}}>
                    <View style={{width:width*0.8347,height:0.144*height,borderRadius:12, backgroundColor:"rgba(20,20,26,0.1)",marginTop:0.0248*height}}>
                        {ERCStatus !== "2" ?
                            (<Text style={{fontSize: 14, marginLeft: 20, marginRight: 20, marginTop: 14, color: '#9292A0'}}>
                            {locale?._('DApp.ETHmappingAddress')}：{"\n"}{ETHAddress}
                             </Text>):
                            (<Text style={{fontSize: 14, marginLeft: 20, marginRight: 20, marginTop: 8, color: '#9292A0'}}>
                                {locale?._('DApp.MappingCompletedTip')}
                            </Text>)
                        }
                        <View style={{flexDirection:"row"}}>
                            <Text style={{ alignSelf: "flex-end", fontSize: 12,marginLeft: 20,
                                marginRight: 0, marginTop: 5,color: '#9292A0'
                            }}>
                                {locale?._('ETHSATBalance')}：
                            </Text>
                            <Text style={{fontSize: 16,marginLeft: 0,marginRight: 0,marginTop: 5,color: '#9292A0'}}>
                                {(ERCBalance==null||ERCBalance=="")?0:parseInt(ERCBalance)/10000}
                            </Text>
                        </View>
                    </View>
                    <TouchableOpacity onPress={()=>mainBTN()}>
                        <View style={{width:0.8293*width,height:0.062*height,borderRadius:16,backgroundColor:'#7367E3',marginTop:0.0248*height-5,alignItems:"center",justifyContent:"center"}}>
                            <Text style={{color:'white',fontSize:19}}> {BTNName}</Text>
                        </View>
                    </TouchableOpacity>

                </View>
                <ScrollView>
                <Text style={{alignSelf:"flex-start",color:"#202020",fontSize:16,marginLeft:15,marginTop:20,marginBottom:10}}>{locale?._('DApp.SmartXService')}</Text>
                <View style={{width:width*0.9,height:width*0.9,borderRadius:16,backgroundColor:'white',alignItems:"center",marginTop:10,marginBottom:20}}>
                    <View style={{flex:1,flexDirection:"row",borderColor:'rgba(0,0,0,0)',borderBottomColor:"#F3F4F5",borderWidth:1}}>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}}
                                              onPress={()=>{
                                                  // navigation.navigate('WebBrowserInfo',{url:"http://192.168.1.104:8181/?address="+wallet.address,showExplore:false,title:"KittySwap"},)
                                                  // navigation.navigate('WebBrowserInfo',{url:"http://103.100.143.65/?address="+wallet.address,showExplore:false,title:"kittySwap.meta"},)
                                                  navigation.navigate('WebBrowserInfo',{url:"http://kittyswap.smartx.one/?address="+wallet.address,showExplore:false,title:"kittySwap.beta"},)
                                                  // navigation.navigate('WebBrowserMessage')
                                                  // console.log("1");
                                                  // Alert.alert('1');
                                              }}
                            >
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={two} style={{width:30,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.DEXExchange')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}}
                                              onPress={()=>{
                                                  navigation.navigate('WebBrowserInfo',{url:"http://106.75.144.161/?address="+wallet.address,showExplore:false,title:"Orca exchange"},)
                                                  // navigation.navigate('WebBrowserInfo',{url:"http://192.168.1.104:8181/?address="+wallet.address,showExplore:false,title:"Orca exchange"},)
                                                  // navigation.navigate('RedEnvelope');
                                                  // setShowMyAlert(true);
                                                  // setAlertInfo("测试MyAlert属性");
                                                  // setAlertTitle("Tips");
                                                  // setBTNcount(2);
                                                  // setInfoline(1);
                                              }
                                              }>
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={six} style={{width:27,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.crossChainAssets')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1}}>
                            {/*测试MyAlert后面删除*/}
                            <TouchableOpacity style={{flex:1}} onPress={()=>{
                                let URL = 'https://miner.smartx.one/?address='+wallet.address;

                                Linking.canOpenURL(URL).then(supported => {
                                    if (!supported) {
                                        console.warn('Can\'t handle url: ' + URL);
                                    } else {
                                        return Linking.openURL(URL);
                                    }
                                }).catch(err => console.error('An error occurred',URL));
                                // navigation.navigate('WebBrowserInfo',{url:"http://192.168.1.102/webTest2.html",address:wallet.address})
                                // navigation.navigate('WebBrowserInfo',{url:"https://miner.smartx.one",address:wallet.address,showExplore:false,title:"水龙头"},)
                                // navigation.navigate('WebBrowserInfo',{url:"http://192.168.1.104/index.html",address:wallet.address,showExplore:false,title:"水龙头"},)
                            }}>
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={five} style={{width:36,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.water')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={{flex:1,flexDirection:"row",borderColor:'rgba(0,0,0,0)',borderBottomColor:"#F3F4F5",borderWidth:1}}>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}} onPress={()=>{
                                // navigation.navigate('RedEnvelopeInfo');
                                navigation.navigate('RedEnvelopeIndex');
                            }}>
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={three} style={{width:27.5,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.redEnvelope')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}}
                                              onPress={()=>{
                                const keyPair = keyPairFromSeed(wallet.seed);
                                console.log(keyPair)
                                let timestamp = new Date().getTime().toString();
                                let data = `${wallet.address}&${timestamp}`;
                                let hash = CryptoJS.SHA256(data).toString();
                                const signAll = keyPairSign(keyPair,hash );
                                navigation.navigate('WebBrowserDM',{url:`https://m.daomin.com?address=${wallet.address}&timestamp=${timestamp}&sign=${signAll}`,address:wallet.address,title:locale._("DApp.daomin")},)
                            }}>
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={daomin} style={{width:35,height:35}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:10}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale._("DApp.daomin")}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1}}>
                            <TouchableOpacity style={{flex:1}} onPress={()=>{
                                // navigation.navigate('RedEnvelopeList');
                                // setShowMyAlert(true);
                                // setAlertTitle("温馨提示");
                                // setAlertInfo("错误原因：hash:hjdgfjuasgyjudgfahjugkfahahjdgfdhjas");
                                // setBTNcount(2);
                            }}>
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={seven} style={{width:29.5,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.DAPPEcology')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={{flex:1,flexDirection:"row",borderColor:'rgba(0,0,0,0)',borderBottomColor:"#F3F4F5",borderWidth:1}}>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}}
                            onPress={()=>{
                                // setShowRedEnvelopeLoad(true);
                                // navigation.navigate('WebBrowserInfo',{showExplore:true})
                                }}
                            >
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={four} style={{width:36,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>{locale?._('DApp.contractStore')}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1,borderWidth:1,borderRightColor:'#F3F4F5',borderTopColor:'rgba(0,0,0,0)',borderBottomColor:'rgba(0,0,0,0)',borderLeftColor:'rgba(0,0,0,0)'}}>
                            <TouchableOpacity style={{flex:1}}
                                              onPress={()=>{
                                                  navigation.navigate('L2_Tabs');
                                              }}
                            >
                                <View style={{alignItems:"center",justifyContent:"center",marginTop:25}}>
                                    <ImageBackground source={four} style={{width:36,height:30}} />
                                </View>
                                <View style={{alignItems:"center",marginTop:15}}>
                                    <Text style={{fontSize:14,color:'#4E5254'}}>SL2</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1}}>
                        </View>
                    </View>

                </View>
                </ScrollView>
            </View>
            {/*测试MyAlert*/}
            <MyAlert visible={showMyAlert} title={AlertTitle} info={AlertInfo} BTNcount={BTNcount}  line={Infoline} back={AlertBack}/>
            {/*<RedEnvelopeLoad visible={showRedEnvelopeLoad} back={RedEnvelopeLoadBack}/>*/}
            <RedEnvelopeLoad visible={showRedEnvelopeLoad} back={RedEnvelopeLoadBack} sender={sender} loadType={loadType} bless={coverTxt}/>
        </View>

    );
}
export default SmartXApp;
